package com.zyd.androidwifi;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.NetworkSpecifier;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkSpecifier;
import android.os.Build;
import android.os.Bundle;
import android.os.PatternMatcher;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.zyd.androidwifi.utils.WifiUtil;

import java.util.ArrayList;
import java.util.List;

public class ListWiFiActivity extends AppCompatActivity {
    private static final String TAG = "ListWiFiActivity-TAG";
    //需要先申请的权限
    String[] permissions = new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };

    private WifiManager mWifiManager;
    private ListView mListView;
    private Button mScanBtn;
    private List<ScanResult> mResults;
    private ArrayList<String> mArrayList = new ArrayList<>();
    private ArrayAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_wi_fi);

        requestPermissions();

        mScanBtn = findViewById(R.id.scanBtn);
        mListView = findViewById(R.id.wifiList);
        //判断定位服务是否开启
        if (!isLocServiceEnable(this)){
            //如果没有开启就让用户打开
            openGPS();
        }

        mScanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scanWiFi();
            }
        });

        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (!mWifiManager.isWifiEnabled()) {
//            Toast.makeText(ListWiFiActivity.this, "WiFi is disabled... we need enable it", Toast.LENGTH_SHORT).show();
            //Enable or disable Wi-Fi.
            //Applications must have the android.Manifest.permission.CHANGE_WIFI_STATE permission to toggle wifi.
//            mWifiManager.setWifiEnabled(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {

                Intent panelIntent = new Intent(Settings.Panel.ACTION_WIFI);

                startActivityForResult(panelIntent, 0);

            } else {
                mWifiManager.setWifiEnabled(true);
            }

        }




        mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, mArrayList);
        mListView.setAdapter(mAdapter);

        scanWiFi();
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("NewApi")
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(ListWiFiActivity.this, mArrayList.get(position), Toast.LENGTH_SHORT).show();
                String networkCapabilities = mArrayList.get(position).split(",")[0];
                String networkSSID = mArrayList.get(position).split(",")[1];
                String networkBSSID = mArrayList.get(position).split(",")[2];
                Log.d(TAG, "onItemClick: networkCapabilities=" + networkCapabilities + " networkSSID=" + networkSSID);
//                connectWiFi(networkCapabilities, networkSSID);
//                connectAppointWiFi(networkSSID);

                WifiUtil wifiUtil = new WifiUtil();
                wifiUtil.init(ListWiFiActivity.this);
//                wifiUtil.changeToWifiAfterQ(networkSSID,"12345678");
                wifiUtil.ConnectToAP(networkSSID,"12345678");

//                connect(networkBSSID,"12345678");

                //跳到手机WIFI设置界面
//                startActivity(new Intent( android.provider.Settings.ACTION_WIFI_SETTINGS));
//                startActivity(new Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY));

            }
        });

    }

    //扫描WiFi
    private void scanWiFi() {
        mArrayList.clear();
        registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        mWifiManager.startScan();
        Toast.makeText(this, "Scanning WiFi...", Toast.LENGTH_SHORT).show();
    }

    // 请求权限
    private void requestPermissions() {
        for (String permission : permissions) {
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(ListWiFiActivity.this, permissions, 100);
            }
        }

    }

    BroadcastReceiver wifiReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                String action = intent.getAction();
                Log.d(TAG, "onReceive:" + action);

                if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                    unregisterReceiver(this);

                    boolean success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
                    if (success) {
                        Toast.makeText(ListWiFiActivity.this, "Scan success", Toast.LENGTH_SHORT).show();

                        mResults = mWifiManager.getScanResults();
                        Log.d(TAG, "onReceive:mResults=" + mResults.size());
                        for (ScanResult scanResult : mResults) {
                            mArrayList.add(scanResult.capabilities + "," + scanResult.SSID + "," + scanResult.BSSID);
                            mAdapter.notifyDataSetChanged();
                        }

                    } else {
                        Toast.makeText(ListWiFiActivity.this, "Scan fail", Toast.LENGTH_SHORT).show();
                    }

                }
            }
        }
    };


    //连接WiFi
    private void connectWiFi(String networkCapabilities, String networkSSID) {

        Toast.makeText(this, "Connecting to network: " + networkSSID, Toast.LENGTH_SHORT).show();


        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View inflateView = layoutInflater.inflate(R.layout.input_wifi_password, null);
        EditText wifiSSID = inflateView.findViewById(R.id.iwp_ssid);
        wifiSSID.setText(networkSSID);
        final EditText wifiPassword = inflateView.findViewById(R.id.iwp_password);

        new AlertDialog.Builder(ListWiFiActivity.this)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setTitle("提示消息")
                .setView(inflateView)
                .setNegativeButton("取消",null)
                .setPositiveButton("连接", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String networkPass = wifiPassword.getText().toString();
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                            NetworkSpecifier specifier =
                                    new WifiNetworkSpecifier.Builder()
                                            .setSsidPattern(new PatternMatcher(networkSSID, PatternMatcher.PATTERN_PREFIX))
                                            .setWpa2Passphrase(networkPass)
                                            .build();

                            NetworkRequest request =
                                    new NetworkRequest.Builder()
                                            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                                            .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                                            .setNetworkSpecifier(specifier)
                                            .build();

                            ConnectivityManager connectivityManager = (ConnectivityManager) ListWiFiActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);

                            ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
                                @Override
                                public void onAvailable(Network network) {
                                    // do success processing here..
                                    Log.d(TAG, "onAvailable " + network.toString());
                                }

                                @Override
                                public void onUnavailable() {
                                    // do failure processing here..

                                    Log.d(TAG, "onUnavailable ");
                                }
                            };
                            connectivityManager.requestNetwork(request, networkCallback);
                            // Release the request when done.
                            // connectivityManager.unregisterNetworkCallback(networkCallback);
                        }
//                        dialogInterface.dismiss();
                    }
                })
                .show();


    }
    //WEP 表示有线等效加密，WPA 表示无线保护访问
    private static final int WIFICIPHER_NOPASS = 0;
    private static final int WIFICIPHER_WEP = 1;
    private static final int WIFICIPHER_WPA = 2;
    private void connectAppointWiFi(String networkSSID){
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View inflateView = layoutInflater.inflate(R.layout.input_wifi_password, null);
        EditText wifiSSID = inflateView.findViewById(R.id.iwp_ssid);
        wifiSSID.setText(networkSSID);
        final EditText wifiPassword = inflateView.findViewById(R.id.iwp_password);
        wifiPassword.setText("12345678");
        new AlertDialog.Builder(ListWiFiActivity.this)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setTitle("提示消息")
                .setView(inflateView)
                .setNegativeButton("取消",null)
                .setPositiveButton("连接", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String networkPass = wifiPassword.getText().toString();
                        int netId = mWifiManager.addNetwork(createWifiConfig(networkSSID, networkPass, WIFICIPHER_WPA));
                        Log.d("ZYDTest", "netId: " + netId);
                        boolean enable = mWifiManager.enableNetwork(netId, true);
                        Log.d("ZYDTest", "enable: " + enable);
                        boolean reconnect = mWifiManager.reconnect();
                        Log.d("ZYDTest", "reconnect: " + reconnect);
//                        dialogInterface.dismiss();
                    }
                })
                .show();

    }

    private WifiConfiguration createWifiConfig(String ssid, String password, int type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";
        Log.d("ZYDTest", "ssid: " + ssid);

        WifiConfiguration tempConfig = isExist(ssid);
        if(tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }

        if(type == WIFICIPHER_NOPASS) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        } else if(type == WIFICIPHER_WEP) {
            config.hiddenSSID = true;
            config.wepKeys[0]= "\""+password+"\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else if(type == WIFICIPHER_WPA) {
            config.preSharedKey = "\""+password+"\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;

        }

        return config;
    }

    private WifiConfiguration isExist(String ssid) {

        @SuppressLint("MissingPermission")//禁止权限检查
        List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();

        for (WifiConfiguration config : configs) {
            if (config.SSID.equals("\""+ssid+"\"")) {
                return config;
            }
        }
        return null;
    }




    public void connect( String wifiName,String wifiPassword) {

//        WifiManager wifiManager = (WifiManager) ListWiFiActivity.this.getSystemService(Service.WIFI_SERVICE);
        WifiManager wifiManager =  (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifiManager.startScan();

        List<ScanResult> list = wifiManager.getScanResults();
        ScanResult targetResult = null;
        for (ScanResult result: list) {
            if (result.SSID.equals(wifiName)) {
                targetResult = result;
                break;
            }
        }

        if (targetResult == null) {
            Toast.makeText(ListWiFiActivity.this, "没有找到WIFI", Toast.LENGTH_SHORT).show();
            return;
        }

        String cap = targetResult.capabilities.toLowerCase();
        Log.d(TAG, "cap:" + cap);

        String password = wifiPassword;//Constant.WIFI_PASSWORD;

        WifiConfiguration config = new WifiConfiguration();
        config.SSID = "\"" + targetResult.SSID + "\"";

        // 加密方式
        if (cap.contains("wpa")) {
            config.preSharedKey = "\"" + password + "\""; // 密码
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        } else if (cap.contains("wep")) {
            int i = password.length();
            if (((i == 10 || i == 26 || i == 58)) && password.matches("[0-9A-Fa-f]*")) {
                config.wepKeys[0] = password;
            } else {
                config.wepKeys[0] = "\"" + password + "\"";
            }
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }

        int netId = wifiManager.addNetwork(config);
        boolean connected = wifiManager.enableNetwork(netId, true);
        Log.d(TAG, "wifi connected:" + connected + "， netId:" + netId);
    }

    /**
     * 手机是否开启位置服务
     */
    public boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }

    /**
     * 用户打开GPS
     *
     * @param
     */
    private void openGPS() {
        new AlertDialog.Builder(ListWiFiActivity.this)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setTitle("提示消息")
                .setMessage("请开启定位")
                .setNegativeButton("取消",null)
                .setPositiveButton("打开", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent,887);
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }

    //返回结果进行监听，成功打开之后在进行定位操作
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode){
            case 887:
                //开启GPS后 扫描WIFI列表
                scanWiFi();
                break;
            default:break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
